package com.lfg.leetcode.leetcode200;


public class No227calculate {

    public static final Integer TYPE_ADD = 1;
    public static final Integer TYPE_MINUS = 2;
    public static final Integer TYPE_MUL = 3;
    public static final Integer TYPE_DIV = 4;
    public static final Integer TYPE_NUM = 5;
    static Token token = null;
    static int index = 0;
    static Character c = null;

    public static void main(String[] args) {


        int ret = calculate(" 3/2 ");
//        int ret = calculate2("1+1");
        System.out.println(ret);
    }

    public static int calculate(String s) {
        move(s);
        token = readToken(s);
        return op(s);
    }

    public static int op(String s) {
        int ret = 0;
        while (token != null) {
            ret += expr(s);


            if (null == token) {
                return ret;
            }

            if (token.type == TYPE_ADD) {
                token = readToken(s);
                ret += expr(s);
            } else if (token.type == TYPE_MINUS) {
                token = readToken(s);
                ret -= expr(s);
            }
            token = readToken(s);
        }
        return ret;
    }

    public static int factor(String s) {
        return token.value;
    }

    public static int expr(String s) {
        int ret = factor(s);
        token = readToken(s);
        if (null == token) {
            return ret;
        }

        if (token.type == TYPE_MUL) {
            token = readToken(s);
            int expr = expr(s);
            return ret * expr;
        } else if (token.type == TYPE_DIV) {
            token = readToken(s);
            int expr = expr(s);
            return ret / expr;
        }
        return ret;
    }

    public static Token readToken(String s) {
        if (c == null) {
            return null;
        }
        Token ret = new Token();

        if (c == '+') {
            ret.type = TYPE_ADD;
            move(s);
            return ret;
        }
        if (c == '-') {
            ret.type = TYPE_MINUS;
            move(s);
            return ret;
        }
        if (c == '*') {
            ret.type = TYPE_MUL;
            move(s);
            return ret;
        }
        if (c == '/') {
            ret.type = TYPE_DIV;
            move(s);
            return ret;
        }

        int data = 0;
        while (c != null && c >= '0' && c <= '9') {
            data = data * 10 + c - '0';
            move(s);
        }
        ret.type = TYPE_NUM;
        ret.value = data;

        return ret;
    }

    private static void move(String s) {
        while (index < s.length()) {
            c = s.charAt(index++);
            if (c != ' ') {
                return;
            }
        }
        c = null;
    }

    static class Token {
        public int type;
        public int value;
    }
}
